package com.kyxx.topics.utils;

import android.app.DownloadManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AlertDialog;

import com.alibaba.fastjson.JSONObject;
import com.kyxx.topics.R;
import com.kyxx.topics.net.OkGoRequest;
import com.kyxx.topics.net.UrlUtils;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;

import java.io.File;
import java.io.FileNotFoundException;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by Administrator on 2016/11/3.
 */
public class ApkUpdateUtils {
    public static void checkUpdate(final Context context, final boolean isAuto) {
//        DownloadManager dManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
//        final Uri downloadFileUri = dManager.getUriForDownloadedFile(PreferenceUtil.getLong("apkId"));
//        downloadFileUri.getPath();
//        if (downloadFileUri != null) {
//            new AlertDialog.Builder(context).setTitle("更新包已下载完毕").setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
//                @Override
//                public void onClick(DialogInterface dialogInterface, int i) {
//                    Intent install = new Intent(Intent.ACTION_VIEW);
//                    install.setDataAndType(downloadFileUri, "application/vnd.android.package-archive");
//                    install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    context.startActivity(install);
//                }
//            }).setNegativeButton("取消",null).show();
//
//            return;
//        }

        HttpParams params = new HttpParams();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("verson_code", getVersionCode(context));
        params.put("json", jsonObject.toString());
        OkGoRequest.post(UrlUtils.appUpdate, context, "apkUpdate", CacheMode.NO_CACHE, params, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                try {
                    final org.json.JSONObject result = new org.json.JSONObject(s);
                    final String url = result.getJSONObject("data").getString("a_download_url");
                    final int versionCode = result.getJSONObject("data").getInt("a_verson_code");
                    final String versionName = result.getJSONObject("data").getString("a_verson_name");
                    final String note = result.getJSONObject("data").getString("a_note");
                    if (versionCode > getVersionCode(context)) {
                        new AlertDialog.Builder(context)
                                .setTitle("更新")
                                .setMessage("版本名称：" + versionName + "\n更新内容：\n" + note)
                                .setNegativeButton("取消", null)
                                .setPositiveButton(
                                        "立即更新",
                                        new DialogInterface.OnClickListener() {

                                            @Override
                                            public void onClick(
                                                    DialogInterface dialog,
                                                    int which) {
                                                startDownload(context, url, "沂蒙" + versionName, "沂蒙" + note, "沂蒙" + versionName);
                                            }
                                        }).show();
                    } else {
                        if (!isAuto)
                            ToastUtils.show(context, "已是最新版本");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }

    public static long startDownload(Context context, String uri, String title, String description, String name) {
        DownloadManager downloadManager;
        downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        DownloadManager.Request req = new DownloadManager.Request(Uri.parse(uri));

        req.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
        //req.setAllowedOverRoaming(false);

        req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

        //设置文件的保存的位置[三种方式]
        //第一种
        //file:///storage/emulated/0/Android/data/your-package/files/Download/update.apk
        try {
            req.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, name + ".apk");
        } catch (Exception e) {
            e.printStackTrace();
        }
        //第二种
        //file:///storage/emulated/0/Download/update.apk
        //req.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "update.apk");
        //第三种 自定义文件路径
        //req.setDestinationUri()

        req.allowScanningByMediaScanner();
        // 设置一些基本显示信息
        req.setTitle(title);
        req.setDescription(description);
        req.setMimeType("application/vnd.android.package-archive");
//        try {
//            downloadManager.openDownloadedFile( downloadManager.enqueue(req));
//        }catch (FileNotFoundException e){
//            e.printStackTrace();
//        }


        //加入下载队列
        long apkId = downloadManager.enqueue(req);
        PreferenceUtil.putLong("apkId", apkId);
        return apkId;

        //long downloadId = dm.enqueue(req);
        //Log.d("DownloadManager", downloadId + "");
        //dm.openDownloadedFile()
    }

    //版本名
    public static String getVersionName(Context context) {
        return getPackageInfo(context).versionName;
    }

    //版本号
    public static int getVersionCode(Context context) {
        return getPackageInfo(context).versionCode;
    }

    private static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;

        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);

            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pi;
    }

    //判断文件是否存在
    public boolean fileIsExists(String strFile) {
        try {
            File f = new File(strFile);
            if (!f.exists()) {
                return false;
            }

        } catch (Exception e) {
            return false;
        }

        return true;
    }
}
